package com.yc.bank.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.yc.bank.entity.Account;
import com.yc.bank.entity.Result;
import com.yc.bank.service.IAccountService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "LoginSerlet", value = "/login.s")
public class LoginSerlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        IAccountService accountService = ctx.getBean(IAccountService.class);

        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");

        //Mybatis-Plus 条件构造器
        //以前使用   但是可能会把字段名写错
//        QueryWrapper<Account> qw = new QueryWrapper<>();
//        qw.eq("id", name);
//        qw.eq("password", pwd);

        //现在使用
        LambdaQueryWrapper<Account> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Account::getId, name);
        lqw.eq(Account::getPassword,pwd);
        List<Account> list = accountService.list(lqw);
        Result result = null;
        try {
            Account account = accountService.getOne(lqw);
            if (account == null){
                result = new Result(0, "用户名或密码错误", null);
            }else{
                result = new Result(1,"登陆成功！",null);
                request.getSession().setAttribute("name", name);
            }
        }catch (RuntimeException e){
            //多个同名记录 ==》  设计问题
            e.printStackTrace();
        }

        String json = new Gson().toJson(result);
        response.getWriter().append(json);
    }
}